﻿using Microsoft.AspNetCore.Mvc;
using LPP.Entity.Orders;
using LPP.Service.OrderServices;
using LPP.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using LPP.Service.TokenService;
using Newtonsoft.Json;

namespace LPP.API.Controllers.OrderControllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class OrderController : ControllerBase
    {
        private readonly IOrderService _orderService;
        private readonly SqlDbContext _context;
        private readonly ITokenService _tokenService;

        public OrderController(IOrderService orderService, SqlDbContext context, ITokenService tokenService)
        {
            _orderService = orderService;
            _context = context;
            _tokenService = tokenService;
        }

        // 创建订单接口
        [HttpPost]
        public async Task<IActionResult> CreateOrder(CreateOrderRequest request)
        {
           
            Console.WriteLine($"Received request: {JsonConvert.SerializeObject(request)}");
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();
                return BadRequest(new { Message = "请求数据验证失败", Errors = errors });
            }
            var userExists = await _context.Users.AnyAsync(u => u.UserID == request.UserID);
            if (!userExists)
            {
                return BadRequest(new { message = "用户不存在。" });
            }
            // 直接使用 AppointmentTime，不需要再次解析
            DateTime appointmentTime = request.AppointmentTime ?? DateTime.MinValue;
            try
            {
                // 创建订单实体
                var order = new Order
                {
                    UserID = request.UserID,
                    Description = request.Description,
                    Amount = request.TotalPrice,
                    CreatedAt = DateTime.Now,
                    Status = OrderStatus.Pending,
                    AppointmentTime = appointmentTime,
                    OrderDetails = request.OrderDetails.Select(item => new OrderDetail
                    {
                        ProductName = item.ProductName,
                        Quantity = item.Quantity,
                        UnitPrice = item.UnitPrice,
                        AppointmentTime = appointmentTime
                    }).ToList()
                };

                // 自动计算收入
                foreach (var detail in order.OrderDetails)
                {
                    detail.UpdateTotalPrice();
                    detail.CalculateIncome();
                }

                // 创建订单
                var createdOrder = await _orderService.CreateOrderAsync(order);
                return Ok(new { Message = "订单创建成功", OrderId = createdOrder.OrderID });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Message = "订单创建失败", Error = ex.Message });
            }
        }

        // 获取未完成的订单详情
        [HttpGet("unfinished-order-details")]
        public async Task<IActionResult> GetUnfinishedOrderDetails()
        {
            try
            {
                var unfinishedOrderDetails = await _context.OrderDetails
                    .Where(od => od.Status == OrderStatus.Pending)
                    .Include(od => od.Order)
                    .ThenInclude(o => o.User)
                    .Select(od => new
                    {
                        od.OrderDetailID,
                        od.OrderID,
                        od.ProductName,
                        od.Quantity,
                        od.UnitPrice,
                        AppointmentTime = od.Order.AppointmentTime,
                        CreatedAt = od.Order.CreatedAt,
                        UserID = od.Order.UserID,
                        Address = _context.Addresses
                            .Where(a => a.UserID == od.Order.UserID)
                            .Select(a => new
                            {
                                a.AddressDetail,
                                a.BuildingNumber,
                                a.City,
                                a.PhoneNumber,
                                a.ContactName
                            })
                            .FirstOrDefault()
                    })
                    .ToListAsync();

                var result = unfinishedOrderDetails.Select(detail => new
                {
                    detail.OrderDetailID,
                    detail.OrderID,
                    detail.ProductName,
                    detail.Quantity,
                    detail.UnitPrice,
                    detail.CreatedAt,
                    detail.UserID,
                    detail.AppointmentTime,
                    Address = detail.Address != null
                     ? $"{detail.Address.City}, {detail.Address.AddressDetail},{detail.Address.BuildingNumber}"
                     : "地址信息未找到",  // 确保在这里结尾
                    ContactName = detail.Address?.ContactName ?? "客户姓名未找到",
                    PhoneNumber = detail.Address?.PhoneNumber ?? "客户电话未找到"
                }).ToList();

                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { Message = "获取未完成订单失败", Error = ex.Message });
            }
        }

        // 根据ID获取订单接口
        [HttpGet("{orderId}")]
        public async Task<IActionResult> GetOrderById(string orderId)
        {
            try
            {
                var order = await _orderService.GetOrderByIdAsync(orderId);
                if (order == null)
                {
                    return NotFound(new { Message = "订单未找到。" });
                }
                return Ok(order);
            }
            catch (Exception ex)
            {
                return BadRequest(new { Message = "获取订单失败", Error = ex.Message });
            }
        }
    }

    public class CreateOrderRequest
    {
        [Required]
        public int UserID { get; set; }
        public string Description { get; set; }
        public List<OrderDetailRequest> OrderDetails { get; set; }
        [Required]
        [Range(0.01, double.MaxValue, ErrorMessage = "TotalPrice 必须大于 0")]
        
        public decimal TotalPrice { get; set; }
        
        [Required(ErrorMessage = "预约时间不能为空")]
        public DateTime? AppointmentTime { get; set; }

        // 添加验证方法
        public bool IsValidAppointmentTime()
        {
            return AppointmentTime.HasValue &&
                   AppointmentTime.Value > DateTime.Now;
        }
    }

    public class OrderDetailRequest
    {
        public string ProductName { get; set; }
        [Required]
        [Range(1, int.MaxValue, ErrorMessage = " " +
            "uantity 必须大于 0")]
        public int Quantity { get; set; }
        [Required]
        [Range(0.01, double.MaxValue, ErrorMessage = "UnitPrice 必须大于 0")]
        public decimal UnitPrice { get; set; }
        
    }
}
